const dotenv = require('./config/dotenv')
const config = require('./config')

const Koa = require('koa')
const app = new Koa()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const swagger = require('./routes/swagger')

const routes = require('./routes')
const errorHandler = require('./config/error')
const { bindRequestContext } = require('./config/asyncContext')

// error handler
onerror(app, errorHandler)

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(process.cwd() + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: { settings: { views: path.join(__dirname, 'views') } },
    map: { 'html': 'nunjucks' }
  }))
  .use(swagger({
    routePrefix: '/swagger',
    swaggerOptions: {
      url: '/swagger.json'
    }
  }, app))
  .use(bindRequestContext)

routes.forEach(middleware => app.use(middleware))
app.on('error', (err, ctx) => {
  console.error(err)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
